package com.zhx.learn.jiguang.handler;

import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.PushPayload;
import com.zhx.learn.jiguang.config.JPushPropertiesConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * describe: 极光推送的Demo
 *  推送的重点在于如何构建 PushPayload
 * @author zhanghaixuan
 * @date 2018/09/09
 **/
@Slf4j
@Component
public class JiGuangPushHandler {


    private JPushClient jPushClient = null;

    @Autowired
    private JPushPropertiesConfig jPushPropertiesConfig;


    @PostConstruct
    public void init(){
        if(jPushPropertiesConfig != null){
            jPushClient = new JPushClient(jPushPropertiesConfig.getMasterSecret(),jPushPropertiesConfig.getAppKey());
        }
    }

    public String push(PushPayload pushPayload){
        try {
            PushResult result = jPushClient.sendPush(pushPayload);
            log.info("Got result - " + result);
            return  result.toString();
        } catch (APIConnectionException e) {
            // Connection error, should retry later
            log.error("连接错误", e);
        } catch (APIRequestException e) {
            // Should review the error, and fix the request
            log.error("发送错误!", e);
            log.info("HTTP Status: " + e.getStatus());
            log.info("Error Code: " + e.getErrorCode());
            log.info("Error Message: " + e.getErrorMessage());
        }


        return "error";
    }



}
